import React from 'react';
import {DropDownMenu, Icon as KIcon} from "@/components/k-view";
import {CheckIcon, HStack, Text, Icon} from "@gluestack-ui/themed";
import {useStore} from "@/store";
import useTool from "@/utils";
import {useTheme} from "@/hooks";
import {channelMaps} from "@/theme/enums/screen";
import {useImmer} from "use-immer";
import {Option} from "@/types/public";


const ChannelDownMenu = () => {
    const channel = useStore.use.channel();
    const changeChannel = useStore.use.changeChannel();
    const {getChannel, objToArr, toUpperCase} = useTool();
    const {layout, colors} = useTheme();
    const channels = objToArr<typeof channelMaps, number>(channelMaps, toUpperCase);
    const [{isOpen}, updateData] = useImmer({
        isOpen: false
    });

    const DropDownItem = (item: Option<number>, index: number): React.ReactNode => {
        const isActive = channel == item.value;
        const color = isActive ? '$primary500' : '$textLight950';
        return (
            <HStack
                w="100%"
                alignItems={"center"}
                justifyContent={"space-between"}
                borderBottomWidth={index == channels.length - 1 ? 0 : 0.5}
                borderColor="$borderLight500"
                py="$2"
                px="$3"
            >
                <Text size="md" color={color}>{item.label}</Text>
                {isActive && <Icon as={CheckIcon} w="$4" h="$4" color={color}/>}
            </HStack>
        )
    }

    // 处理频道切换
    function handleChannelChange(keys: any) {
        let index = Number(keys?.currentKey);
        let channel = channels[index].value;
        changeChannel(channel);
    }

    function setIsOpen(v: boolean) {
        updateData(draft => {
            draft.isOpen = v;
        });
    }

    return (
        <DropDownMenu
            width={200}
            menus={channels}
            itemRender={DropDownItem}
            placement={"bottom"}
            onOpen={() => setIsOpen(true)}
            onClose={() => setIsOpen(false)}
            onSelectionChange={handleChannelChange}
        >
            <HStack
                alignItems={"center"}
                space={"xs"}
            >
                <Text size="sm" color="$textLight950">{getChannel(channel)}数据</Text>
                <KIcon
                    name={'\ue627'}
                    size={12}
                    color={colors.textLight950}
                    isRotate={isOpen}
                />
            </HStack>
        </DropDownMenu>
    );
};

export default ChannelDownMenu;